<template>
  <div id="homePage">
    <!-- 标题与副标题 -->
    <div class="hero">
      <h1 class="title">一句话 · 生成你所想</h1>
      <p class="subtitle">与 AI 对话轻松创建应用和网站</p>
    </div>

    <!-- 提示词输入框 -->
    <a-card class="prompt-card">
      <a-space direction="vertical" style="width: 100%">
        <a-textarea
          v-model:value="prompt"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :maxlength="500"
          placeholder="使用 NoCode 创建一个高效的小工具，帮我计算……"
        />
        <div class="prompt-actions">
          <a-input v-model:value="appName" placeholder="应用名称（可选）" style="max-width: 320px" />
          <a-select v-model:value="codeGenType" style="max-width: 220px" :options="codeGenTypeOptions" />
          <a-button type="primary" :loading="creating" @click="handleCreate">生成应用</a-button>
        </div>
      </a-space>
    </a-card>

    <!-- 我的应用列表 -->
    <a-card class="list-card" title="我的作品">
      <a-form layout="inline" :model="myQuery" @finish="fetchMyApps">
        <a-form-item>
          <a-input v-model:value="myQuery.appName" placeholder="按名称搜索" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
      <a-list :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4 }" :data-source="myApps">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card :title="item.appName" :hoverable="true">
              <img v-if="item.cover" :src="item.cover" class="cover" />
              <template #actions>
                <a @click="goChat(item.id)">对话生成</a>
                <a @click="goEdit(item.id)">编辑</a>
              </template>
            </a-card>
          </a-list-item>
        </template>
      </a-list>
      <a-pagination
        style="margin-top: 12px; text-align: right"
        :current="myQuery.pageNum"
        :page-size="myQuery.pageSize"
        :total="myTotal"
        :show-total="(t:number)=>`共 ${t} 条`"
        @change="onMyPageChange"
      />
    </a-card>

    <!-- 精选应用列表 -->
    <a-card class="list-card" title="精选案例">
      <a-form layout="inline" :model="featuredQuery" @finish="fetchFeaturedApps">
        <a-form-item>
          <a-input v-model:value="featuredQuery.appName" placeholder="按名称搜索" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
      <a-list :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4 }" :data-source="featuredApps">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card :title="item.appName" :hoverable="true">
              <img v-if="item.cover" :src="item.cover" class="cover" />
              <template #actions>
                <a @click="goChat(item.id)">体验</a>
              </template>
            </a-card>
          </a-list-item>
        </template>
      </a-list>
      <a-pagination
        style="margin-top: 12px; text-align: right"
        :current="featuredQuery.pageNum"
        :page-size="featuredQuery.pageSize"
        :total="featuredTotal"
        :show-total="(t:number)=>`共 ${t} 条`"
        @change="onFeaturedPageChange"
      />
    </a-card>
  </div>
  
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { addApp, listFeaturedApps, listMyApps } from '@/api/appController.ts'

const router = useRouter()

const prompt = ref('')
const appName = ref('')
const codeGenType = ref('html')
const codeGenTypeOptions = [
  { label: '单文件', value: 'html' },
  { label: '多文件', value: 'multi-file' },
]
const creating = ref(false)

const handleCreate = async () => {
  if (!prompt.value.trim()) {
    message.warning('请输入提示词')
    return
  }
  creating.value = true
  try {
    const res = await addApp({ appName: appName.value || '我的新应用', initPrompt: prompt.value, codeGenType: codeGenType.value })
    if (res.data.code === 0 && res.data.data) {
      const appId = res.data.data
      router.push(`/app/chat/${appId}`)
    } else {
      message.error('创建失败：' + res.data.message)
    }
  } finally {
    creating.value = false
  }
}

// 我的应用
const myApps = ref<API.AppVO[]>([])
const myTotal = ref(0)
const myQuery = reactive<API.AppQueryRequest>({ pageNum: 1, pageSize: 12, appName: '' })
const fetchMyApps = async () => {
  const res = await listMyApps({ ...myQuery })
  if (res.data.data) {
    myApps.value = res.data.data.records ?? []
    myTotal.value = res.data.data.totalRow ?? 0
  }
}

const onMyPageChange = (p: number, ps: number) => {
  myQuery.pageNum = p
  myQuery.pageSize = ps
  fetchMyApps()
}

// 精选应用
const featuredApps = ref<API.AppVO[]>([])
const featuredTotal = ref(0)
const featuredQuery = reactive<API.AppQueryRequest>({ pageNum: 1, pageSize: 12, appName: '', featured: true })
const fetchFeaturedApps = async () => {
  const res = await listFeaturedApps({ ...featuredQuery })
  if (res.data.data) {
    featuredApps.value = res.data.data.records ?? []
    featuredTotal.value = res.data.data.totalRow ?? 0
  }
}

const onFeaturedPageChange = (p: number, ps: number) => {
  featuredQuery.pageNum = p
  featuredQuery.pageSize = ps
  fetchFeaturedApps()
}

const goChat = (id?: any) => {
  if (!id) return
  router.push(`/app/chat/${id}`)
}
const goEdit = (id?: any) => {
  if (!id) return
  router.push(`/app/edit/${id}`)
}

onMounted(() => {
  fetchMyApps()
  fetchFeaturedApps()
})
</script>

<style scoped>
.hero{ text-align:center; padding:24px 0 }
.title{ font-size:32px; margin-bottom:8px; color:#0f172a }
.subtitle{ color:#64748b }
.prompt-card{ margin:16px 0 }
.prompt-actions{ display:flex; gap:12px; align-items:center }
.list-card{ margin-top:16px }
.cover{ width:100%; height:140px; object-fit:cover; border-radius:6px }
</style>
